<template>
  <div class="import-export-container">
    <div class="page-header">
      <h2>数据导入导出</h2>
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/supplier' }">供应商管理</el-breadcrumb-item>
        <el-breadcrumb-item>数据导入导出</el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <el-card class="box-card">
      <div slot="header" class="card-header">
        <span>Excel数据导入</span>
      </div>
      <div class="import-section">
        <el-upload
          class="upload-demo"
          drag
          action="http://localhost:5000/api/suppliers/import"
          :on-success="handleUploadSuccess"
          :on-error="handleUploadError"
          :on-change="handleChange"
          :before-upload="beforeUpload"
          :limit="1"
          :file-list="fileList"
          accept=".xlsx, .xls">
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <div class="el-upload__tip" slot="tip">只能上传xlsx/xls文件，且不超过10MB</div>
        </el-upload>
        
        <div v-if="importStatus" :class="['import-status', importStatus.type]">
          <i :class="importStatus.icon"></i>
          <span>{{importStatus.message}}</span>
        </div>
      </div>
    </el-card>

    <el-card class="box-card export-card">
      <div slot="header" class="card-header">
        <span>Excel数据导出</span>
      </div>
      <div class="export-section">
        <p>导出当前系统中的所有供应商数据为Excel文件</p>
        <el-button type="primary" @click="exportData" :loading="isExporting">导出Excel</el-button>
        <el-button @click="downloadTemplate" :loading="isDownloadingTemplate">下载Excel模板</el-button>
      </div>
    </el-card>
    
    <el-card class="box-card guide-card">
      <div slot="header" class="card-header">
        <span>使用说明</span>
      </div>
      <div class="guide-section">
        <h3>导入Excel文件格式要求</h3>
        <p>上传的Excel文件必须包含以下列（表头）：</p>
        <ul>
          <li>公司名称（必填）</li>
          <li>简称</li>
          <li>主营业务</li>
          <li>联系方式</li>
          <li>总部地址</li>
          <li>成立时间</li>
        </ul>
        
        <h3>步骤说明</h3>
        <ol>
          <li>点击"下载Excel模板"获取标准格式模板</li>
          <li>在Excel中填入供应商数据</li>
          <li>将填好的Excel文件拖拽到上传区域或点击上传</li>
          <li>上传成功后，系统会将数据导入到数据库</li>
        </ol>
      </div>
    </el-card>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      fileList: [],
      isUploading: false,
      isExporting: false,
      isDownloadingTemplate: false,
      importStatus: null
    }
  },
  methods: {
    handleChange(file) {
      this.fileList = [file];
    },
    
    beforeUpload(file) {
      const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' || 
                     file.type === 'application/vnd.ms-excel';
      const isLt10M = file.size / 1024 / 1024 < 10;

      if (!isExcel) {
        this.$message.error('只能上传Excel文件！');
        return false;
      }
      if (!isLt10M) {
        this.$message.error('文件大小不能超过10MB！');
        return false;
      }
      
      this.importStatus = null;
      return true;
    },
    
    handleUploadSuccess(response) {
      if (response.status === 'success') {
        this.importStatus = {
          type: 'success',
          icon: 'el-icon-success',
          message: response.message
        };
        
        this.$message.success(response.message);
        
        // 刷新供应商列表（如果在同一个页面）
        if (this.$parent && this.$parent.getSupplierList) {
          this.$parent.getSupplierList();
        }
      } else {
        this.handleUploadError(response);
      }
    },
    
    handleUploadError(error) {
      let errorMessage = '上传失败';
      
      if (error.response && error.response.data) {
        errorMessage = error.response.data.message || errorMessage;
      } else if (error.message) {
        errorMessage = error.message;
      }
      
      this.importStatus = {
        type: 'error',
        icon: 'el-icon-error',
        message: errorMessage
      };
      
      this.$message.error(errorMessage);
    },
    
    // 导出数据为Excel
    exportData() {
      this.isExporting = true;
      
      axios.get('/api/suppliers/export', { responseType: 'blob' })
        .then(response => {
          // 检查是否是JSON响应（错误消息）
          const contentType = response.headers['content-type'];
          if (contentType && contentType.includes('application/json')) {
            return response.data.text().then(text => {
              const error = JSON.parse(text);
              throw new Error(error.message || '导出失败');
            });
          }
          
          // 如果是文件，创建下载链接
          const blob = new Blob([response.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
          const link = document.createElement('a');
          link.href = window.URL.createObjectURL(blob);
          link.download = `供应商数据_${new Date().toISOString().split('T')[0]}.xlsx`;
          link.click();
          window.URL.revokeObjectURL(link.href);
          
          this.$message.success('导出成功');
        })
        .catch(error => {
          console.error('导出出错:', error);
          this.$message.error('导出失败: ' + (error.message || error));
        })
        .finally(() => {
          this.isExporting = false;
        });
    },
    
    // 下载Excel模板
    downloadTemplate() {
      this.isDownloadingTemplate = true;
      
      axios.get('/api/suppliers/template', { responseType: 'blob' })
        .then(response => {
          // 检查是否是JSON响应（错误消息）
          const contentType = response.headers['content-type'];
          if (contentType && contentType.includes('application/json')) {
            return response.data.text().then(text => {
              const error = JSON.parse(text);
              throw new Error(error.message || '下载模板失败');
            });
          }
          
          // 如果是文件，创建下载链接
          const blob = new Blob([response.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
          const link = document.createElement('a');
          link.href = window.URL.createObjectURL(blob);
          link.download = `供应商数据模板.xlsx`;
          link.click();
          window.URL.revokeObjectURL(link.href);
          
          this.$message.success('模板下载成功');
        })
        .catch(error => {
          console.error('下载模板出错:', error);
          this.$message.error('下载模板失败: ' + (error.message || error));
        })
        .finally(() => {
          this.isDownloadingTemplate = false;
        });
    }
  }
}
</script>

<style scoped>
.import-export-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  font-size: 18px;
}

.box-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.import-section, .export-section, .guide-section {
  padding: 10px 0;
}

.import-status {
  margin-top: 15px;
  padding: 10px;
  border-radius: 4px;
  display: flex;
  align-items: center;
}

.import-status.success {
  background-color: #f0f9eb;
  color: #67c23a;
}

.import-status.error {
  background-color: #fef0f0;
  color: #f56c6c;
}

.import-status i {
  margin-right: 10px;
  font-size: 18px;
}

.export-section {
  display: flex;
  align-items: center;
  gap: 15px;
}

.export-section p {
  margin: 0;
}

.guide-card {
  margin-top: 30px;
}

.guide-section h3 {
  font-size: 16px;
  color: #303133;
  margin-top: 0;
  margin-bottom: 10px;
}

.guide-section p {
  margin: 10px 0;
}

.guide-section ul, .guide-section ol {
  padding-left: 20px;
  margin: 10px 0;
}

.guide-section li {
  margin-bottom: 5px;
}
</style> 